package com.example.star.view.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.star.R;
import com.example.star.api_service.ApiPerimeter;
import com.example.star.entity.Perimeter;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;
import com.example.star.utils.ImageUploadUtils;
import com.example.star.view.fragment.HomeFragment;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PerimeterActivity extends AppCompatActivity {

    private ImageButton backButton;
    private TextView toolbarTitle;
    private ImageView addImage;
    private EditText starNameEditText;
    private EditText titleEditText;
    private EditText productTypeEditText;
    private EditText pricesEditText;
    private EditText freightEditText;
    private EditText deliveryAddressEditText;
    private Button publishButton;
    private String selectedImagePath;
    private String userName; // 用于存储用户名
    private ImageUploadUtils imageUploadUtils;
    private boolean isAdmin = false;

    private static final String TAG = "PerimeterActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 加载自定义布局
        setContentView(R.layout.activity_perimeter);

        // 从 SharedPreferences 中读取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        userName = sharedPreferences.getString("username", "");

        // 初始化视图
        initViews();

        // 初始化 ImageUploadUtils
        imageUploadUtils = new ImageUploadUtils(this, addImage);

        // 获取用户信息并检查是否为管理员
        getUserInfo();

        // 设置点击事件监听器
        setupClickListeners();
    }

    private void initViews() {
        backButton = findViewById(R.id.back_button);
        toolbarTitle = findViewById(R.id.toolbar_title);
        addImage = findViewById(R.id.add_image);
        starNameEditText = findViewById(R.id.starname);
        titleEditText = findViewById(R.id.title);
        productTypeEditText = findViewById(R.id.producttype);
        pricesEditText = findViewById(R.id.prices);
        freightEditText = findViewById(R.id.freight);
        deliveryAddressEditText = findViewById(R.id.delivery_address);
        publishButton = findViewById(R.id.btnPerimeter);
    }

    private void setupClickListeners() {
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理返回按钮点击事件，例如返回上一页
                finish();
            }
        });

        addImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageUploadUtils.startImageUpload();
            }
        });

        // 设置发布按钮点击事件
        publishButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查是否是管理员或用户名以"SJ"开头
                if (!isAdmin && (userName == null ||!userName.startsWith("SJ"))) {
                    Toast.makeText(PerimeterActivity.this, "您权限不足", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 进行输入校验
                if (validateInput()) {
                    // 获取用户输入的信息
                    String imageResource = selectedImagePath;
                    String starName = starNameEditText.getText().toString();
                    String title = titleEditText.getText().toString();
                    String productType = productTypeEditText.getText().toString();
                    String prices = pricesEditText.getText().toString();
                    String freight = freightEditText.getText().toString();
                    String deliveryAddress = deliveryAddressEditText.getText().toString();

                    // 创建 Perimeter 对象
                    Perimeter perimeter = new Perimeter(imageResource, starName, title, productType, prices, freight, deliveryAddress);
                    perimeter.setUserName(userName); // 使用读取到的用户名
                    // 发送 POST 请求保存到服务器
                    sendPostRequest(perimeter);

                }
            }
        });
    }

    private void getUserInfo() {
        ApiPerimeter apiPerimeter = ApiClient.getApiPerimeter();
        Call<User> call = apiPerimeter.getUserByUsername(userName);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                    User user = response.body();
                    if (user != null) {
                        isAdmin = user.isAdmin();
                    }
                } else {
                    try {
                        String errorBody = response.errorBody().string();
                        Log.d(TAG, "Response error body: " + errorBody);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(PerimeterActivity.this, "获取用户信息失败，状态码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(PerimeterActivity.this, "获取用户信息失败，网络请求出错: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        imageUploadUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        imageUploadUtils.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        selectedImagePath = imageUploadUtils.getSelectedImagePath();
    }

    private boolean validateInput() {
        // 校验明星姓名是否为空
        if (TextUtils.isEmpty(starNameEditText.getText().toString())) {
            Toast.makeText(this, "明星姓名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验货品标题是否为空
        if (TextUtils.isEmpty(titleEditText.getText().toString())) {
            Toast.makeText(this, "货品标题不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验周边类别是否为空
        if (TextUtils.isEmpty(productTypeEditText.getText().toString())) {
            Toast.makeText(this, "周边类别不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验货品单价是否为空
        if (TextUtils.isEmpty(pricesEditText.getText().toString())) {
            Toast.makeText(this, "货品单价不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验货品运费是否为空
        if (TextUtils.isEmpty(freightEditText.getText().toString())) {
            Toast.makeText(this, "货品运费不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验发货地址是否为空
        if (TextUtils.isEmpty(deliveryAddressEditText.getText().toString())) {
            Toast.makeText(this, "发货地址不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private void sendPostRequest(Perimeter perimeter) {
        ApiPerimeter apiPerimeter = ApiClient.getApiPerimeter();
        Call<Perimeter> call = apiPerimeter.savePerimeter(perimeter);
        call.enqueue(new Callback<Perimeter>() {
            @Override
            public void onResponse(Call<Perimeter> call, Response<Perimeter> response) {
                int statusCode = response.code();
                Log.d(TAG, "Response status code: " + statusCode);
                if (response.isSuccessful()) {
                    Toast.makeText(PerimeterActivity.this, "周边发布成功", Toast.LENGTH_SHORT).show();
                    // 发布成功后返回 HomeFragment
                    finish();
                } else {
                    try {
                        String errorBody = response.errorBody().string();
                        Log.d(TAG, "Response error body: " + errorBody);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(PerimeterActivity.this, "周边发布失败，状态码: " + statusCode, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Perimeter> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(PerimeterActivity.this, "发布失败，网络请求出错: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}